import {
  createEntityAdapter,
  createSlice,
  PayloadAction,
} from "@reduxjs/toolkit";
import { AppState } from "@store/index";

const searchResultEntityAdaptor = createEntityAdapter<News>({
  selectId: (news) => news.art_id,
});

export const searchResultSlice = createSlice({
  name: "searchResult",
  initialState: searchResultEntityAdaptor.getInitialState(),
  reducers: {
    // 保存搜索结果
    saveSearchResult(state, action: PayloadAction<News[]>) {
      searchResultEntityAdaptor.addMany(state, action.payload);
    },
    // 清空搜索结果
    clearSearchResult(state) {
      searchResultEntityAdaptor.removeAll(state);
    },
  },
});

export const searchResultSelectors =
  searchResultEntityAdaptor.getSelectors<AppState>(
    (state) => state.searchResult
  );

export const { saveSearchResult, clearSearchResult } =
  searchResultSlice.actions;
